package com.info.zhiduoduo.weixin.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.maker.StudioState;
import com.info.zhiduoduo.common.constants.partner.PartnerBrokerageState;
import com.info.zhiduoduo.common.constants.partner.PartnerCrowdsourceCostState;
import com.info.zhiduoduo.common.constants.partner.RemitType;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.formbean.BaseAuthInfo;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.FileUtil;
import com.info.zhiduoduo.common.utils.MD5Util;
import com.info.zhiduoduo.common.utils.QrcodeUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.formbean.ListPartnerStudioWithdrawsFromBean;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.CorePartnerService;
import com.info.zhiduoduo.core.service.WxPartnerMessageService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.impl.BankCardElementCertificationService;
import com.info.zhiduoduo.repository.dto.marketingcooperative.MarketingCooperativePartnerDto;
import com.info.zhiduoduo.repository.dto.partner.*;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.marketingcooperative.MarketingCooperativeRecord;
import com.info.zhiduoduo.repository.entity.partner.Partner;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccount;
import com.info.zhiduoduo.repository.entity.partner.PartnerBankcard;
import com.info.zhiduoduo.repository.entity.partner.PartnerBrokerage;
import com.info.zhiduoduo.repository.entity.partner.PartnerRecommendCompany;
import com.info.zhiduoduo.repository.entity.partner.PartnerShareImg;
import com.info.zhiduoduo.repository.entity.partner.PartnerShareUser;
import com.info.zhiduoduo.repository.entity.system.BusinessManager;
import com.info.zhiduoduo.repository.mapper.partner.PartnerAccountMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerAccountflowMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBankcardMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMonthlyCrowdCostMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMonthlyCrowdCostMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerRecommendCompanyMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerStudioWithdrawMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerVaccineRecordMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerWithdrawMapper;
import com.info.zhiduoduo.weixin.dto.partner.RegPartnerDto;
import com.info.zhiduoduo.weixin.formbean.partner.AddShareUserFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.AuthenticationFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.BindStudioFromBean;
import com.info.zhiduoduo.weixin.formbean.partner.CommissionFlowFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.ListWithdrawRecordFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.MonthlyCostFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.OrgPartnerLoginFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.PartnerBankcardAuthFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.PartnerDfPwdFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.PartnerForgetDfPwdFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.PartnerVaccineRecordFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.PartnerVaccineRecordListFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.RecommendCompanyListFormBean;
import com.info.zhiduoduo.weixin.formbean.partner.SubmitRecommendCompanyFormBean;
import com.info.zhiduoduo.weixin.formbean.system.RegFormBean;
import com.info.zhiduoduo.wxsdk.WxApiService;
import com.info.zhiduoduo.wxsdk.config.WxPartnerConfig;
import com.info.zhiduoduo.wxsdk.domain.app.WxAuthorizeAccessToken;
import com.info.zhiduoduo.wxsdk.domain.app.WxAuthorizeUserInfo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import static com.info.zhiduoduo.common.constants.Constants.partner_state_2;

@Slf4j
@Service
public class PartnerService extends BaseService {

	@Autowired
	PartnerBrokerageMapper partnerBrokerageMapper;
	@Autowired
	PartnerBankcardMapper partnerBankcardMapper;
	@Resource
	PartnerMapper partnerMapper;
	@Resource
	PartnerAccountMapper partnerAccountMapper;
	@Resource
	PartnerAccountflowMapper partnerAccountflowMapper;
	@Resource
	PartnerWithdrawMapper partnerWithdrawMapper;
	@Resource
	PartnerCompanyMapper partnerCompanyMapper;
	@Autowired
	PartnerRecommendCompanyMapper partnerRecommendCompanyMapper;
	@Autowired
	PartnerStudioWithdrawMapper partnerStudioWithdrawMapper;
	@Autowired
	PartnerMonthlyCrowdCostMapper partnerMonthlyCrowdCostMapper;
	@Resource
	PartnerVaccineRecordMapper partnerVaccineRecordMapper;

	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	PayConfig payConfig;
	@Autowired
	UploadPathConfig uploadPathConfig;

	@Autowired
	WxPartnerConfig wxPartnerConfig;

	@Autowired
	WxApiService wxApiService;
	@Autowired
	WxPartnerMessageService wxPartnerMessageService;
	@Autowired
	CorePartnerService corePartnerService;
	@Autowired
	CommonService commonService;
	@Autowired
	MarketingCooperativeService marketingCooperativeService;

	@Resource
	PartnerCompanyMonthlyCrowdCostMapper partnerCompanyMonthlyCrowdCostMapper;
	@Autowired
	BankCardElementCertificationService bankCardElementCertificationService;
	/**
	 * 获取合伙人信息
	 *
	 * @param baseAuthInfo
	 * @return
	 */
	public SmartResult getPartnerInfo(BaseAuthInfo baseAuthInfo) {
		SmartResult smartResult = new SmartResult();
		PartnerDetailDto partnerDetailDto = partnerMapper.getPartnerDetail(baseAuthInfo.getUserid());
		if (null == partnerDetailDto) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		}
		List<MarketingCooperativePartnerDto> getMarketingCooperativeList = partnerMapper.getMarketingCooperativeList(partnerDetailDto.getPartnerid());
		partnerDetailDto.setMarketingCooperativeList(getMarketingCooperativeList);
		smartResult.setObject(partnerDetailDto);
		return smartResult;
	}

	/**
	 * 手机短信验证
	 *
	 * @param formBean
	 * @return
	 */
	@Transactional
	public SmartResult regPartner(BaseSimpleFormBean<RegFormBean> formBean) {
		SmartResult smartResult = new SmartResult();
		RegFormBean regFormBean = formBean.getReqdata();

		if (null == regFormBean || StringUtil.isEmpty(regFormBean.getPhone()) || StringUtil.isEmpty(regFormBean.getVerifycode()) ||
				formBean.getUserid() == 0) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int partnerid = formBean.getUserid();
		String phone = regFormBean.getPhone();

		//校验用户
		Partner partner = new Partner().selectById(partnerid);
		if (null == partner) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		} else if (partner.getState() >= partner_state_2) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_506);
			return smartResult;
		}

		//获取手机短信验证码
		String verifyCode = regFormBean.getVerifycode();
		commonService.checkPhoneVerifyCode(phone, verifyCode);

		//验证合伙人的邀请码是否有效
		String inviteCode = regFormBean.getInviteCode();
		if (StringUtil.isNotEmpty(inviteCode)) {
			int count = new PartnerAccount().selectCount(Condition.create().eq("promo_code", inviteCode));
			if (count == 0) {
				return smartResult(StatusMsg.StatusMsg_505);
			}
		}

		//查看合伙人是否已经注册
		Partner existPartner = partnerMapper.checkPartnerExistByPhone(phone);
		RegPartnerDto regPartnerDto = null;
		if (null != existPartner) {
			/*returnValue.setStateMsg(StateMsg.StatusMsg_122);
			return returnValue;*/

			//切换合伙人的公众号后，转移旧公众号上的合伙人到新公众号上，根据手机号识别。
			existPartner.setOpenid(partner.getOpenid())
					.setUnionid(partner.getUnionid())
					.setAvatar(partner.getAvatar())
					.setNickname(partner.getNickname())
					.setSex(partner.getSex());

			if (existPartner.updateById()) {
				partnerMapper.delPartner(partner.getPartnerid());
				regPartnerDto = new RegPartnerDto(existPartner.getPartnerid(), 1);
				partner = existPartner;
			}
		} else {
			//更新合伙人手机号
			partner.setPhone(phone).setInviteCode(inviteCode);
			partner.setState(partner_state_2);

			if (partner.updateById()) {
				//注册成功，创建创客账户
				new PartnerAccount().setPartnerid(partner.getPartnerid())
						.setPromoCode(String.valueOf(partnerid + 100))
						.setRealnameAuth(1)
						.insert();

				regPartnerDto = new RegPartnerDto(partnerid, 0);
			}
		}

		if (regPartnerDto != null) {
			// 合销云注册
			if (regFormBean.getMarketingCooperativeCompid() > 0) {
				marketingCooperativeService.create(partnerid, regFormBean.getMarketingCooperativeCompid());
			}
			return smartResult(regPartnerDto);
		}
		return SmartResult.ofOptFail();

	}

	/**
	 * 实名认证
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult realNameAuthentication(BaseSimpleFormBean<AuthenticationFormBean> formBean) {
		SmartResult smartResult = new SmartResult();
		AuthenticationFormBean reqdata = formBean.getReqdata();
		//判断传回参数是否为空
		if (null == reqdata) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		//获取当前登录者IDp
		int partnerid = formBean.getUserid();
		//查询是否存在合伙人
		Partner partner = new Partner().selectById(partnerid);
		if (null == partner) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		}
		PartnerAccount partnerAccount = partnerAccountMapper.getPartnerAccountByPartnerId(partnerid);
		PartnerAccount existAccount = new PartnerAccount().selectOne(
				Condition.create().eq("idno", reqdata.getIdno()).eq("identity_type", reqdata.getIdentityType()));
		if (null == partnerAccount) {
			//第一次添加
			if (existAccount != null) return SmartResult.fail(StatusMsg.StatusMsg_521);

			partnerAccount = new PartnerAccount().setPartnerid(partnerid).setRealnameAuth(Constants.partner_auth_2);
			BeanUtils.copyProperties(reqdata, partnerAccount);
			//新增
			partnerAccount.insert();
		} else {
			//重新提交资料
			if (existAccount != null && !existAccount.getPartnerid().equals(partnerid)) {
				// 新身份证号已经有其他人注册过了
				return SmartResult.fail(StatusMsg.StatusMsg_521);
			}
			BeanUtils.copyProperties(reqdata, partnerAccount);
			partnerAccount.setRealnameAuth(Constants.realname_auth_2);
			partnerAccount.updateById();
		}
		return smartResult;
	}

	//微信查询接口

	/**
	 * 查询合伙人最新佣金记录
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<PartnerCommissionInfoDto> getPartnerCommissionInfo(BaseSimpleFormBean formBean) {
		SmartResult<PartnerCommissionInfoDto> smartResult = new SmartResult<>();
		int partnerId = formBean.getUserid();
		if (partnerId == 0) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		//查询合伙人
		PartnerAccount partnerAccount = partnerAccountMapper.getPartnerAccountByPartnerId(partnerId);
		if (null == partnerAccount) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		}
		PartnerCommissionInfoDto partnerCommissionInfoDto = new PartnerCommissionInfoDto();
		partnerCommissionInfoDto.setRealname(partnerAccount.getRealname());
		partnerCommissionInfoDto.setPromoCode(partnerAccount.getPromoCode());
		//查询合伙人所有已结算的佣金记录
		List<PartnerBrokerage> partnerBrokerageList = partnerBrokerageMapper.getPartnerAndCompanyAllCommission(0, partnerId);
		if (null != partnerBrokerageList) {
			List<PartnerCommissionRecordDto> partnerCommissionRecordDtoList = new ArrayList<>();
			//只取最新的10条
			int i = 0;
			for (PartnerBrokerage partnerBrokerage : partnerBrokerageList) {
				i += 1;
				if (i == 10) {
					break;
				}
				PartnerCommissionRecordDto partnerCommissionRecordDto = new PartnerCommissionRecordDto();
				partnerCommissionRecordDto.setCreatetime(partnerBrokerage.getCreatetime());
				partnerCommissionRecordDto.setBrokerageid(partnerBrokerage.getBrokerageid());
				Company company = new Company().selectById(partnerBrokerage.getCompid());
				if (company != null) {
					partnerCommissionRecordDto.setCompname(company.getCompname());
				}
				partnerCommissionRecordDto.setBrokerage(partnerBrokerage.getBrokerage());
				partnerCommissionRecordDtoList.add(partnerCommissionRecordDto);
			}
			//  项目佣金
			BigDecimal zddUnremittedbrokerage = partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerId,
					PartnerBrokerageState.SETTLED);
			BigDecimal zddRemittedBrokerage = partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerId,
					PartnerBrokerageState.WITHDRAWED);
			zddRemittedBrokerage = zddRemittedBrokerage.add(
					partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerId, PartnerBrokerageState.WITHDRAWING));
			// 智众包项目佣金
			BigDecimal crowdsourceUnremittedBrokerage = partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerId,
					PartnerBrokerageState.SETTLED);
			BigDecimal crowdsourceRemittedBrokerage = partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerId,
					PartnerBrokerageState.WITHDRAWED);
			crowdsourceRemittedBrokerage = crowdsourceRemittedBrokerage.add(
					partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerId, PartnerBrokerageState.WITHDRAWING));
			// 智众包成本佣金
			BigDecimal crowdsourceCostUnremittedBrokerage = partnerMonthlyCrowdCostMapper.sumPartnerBrokerage(partnerId,
					PartnerCrowdsourceCostState.UNSETTLED);
			BigDecimal crowdsourceCostRemittedBrokerage = partnerMonthlyCrowdCostMapper.sumPartnerBrokerage(partnerId,
					PartnerCrowdsourceCostState.WITHDRAWED);
			crowdsourceCostRemittedBrokerage = crowdsourceCostRemittedBrokerage.add(
					partnerMonthlyCrowdCostMapper.sumPartnerBrokerage(partnerId, PartnerCrowdsourceCostState.WITHDRAWING));

			partnerCommissionInfoDto.setZddRemittedBrokerage(zddRemittedBrokerage);
			partnerCommissionInfoDto.setZddUnremittedBrokerage(zddUnremittedbrokerage);
			partnerCommissionInfoDto.setCrowdsourceRemittedBrokerage(crowdsourceRemittedBrokerage);
			partnerCommissionInfoDto.setCrowdsourceUnremittedBrokerage(crowdsourceUnremittedBrokerage);
			partnerCommissionInfoDto.setCrowdsourceCostRemittedBrokerage(crowdsourceCostRemittedBrokerage);
			partnerCommissionInfoDto.setCrowdsourceCostUnremittedBrokerage(crowdsourceCostUnremittedBrokerage);

			partnerCommissionInfoDto.setCount(partnerBrokerageList.size());
			partnerCommissionInfoDto.setPartnerCommissionRecordDtos(partnerCommissionRecordDtoList);
		}
		return smartResult(partnerCommissionInfoDto);
	}

	/**
	 * 查询合伙人佣金流水
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<PartnerCommissionFlowDto> getPartnerCommissionFlowingWater(BaseSimpleFormBean<CommissionFlowFormBean> formBean) {
		SmartResult<PartnerCommissionFlowDto> smartResult = new SmartResult<>();
		int partnerId = formBean.getUserid();
		if (partnerId == 0) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		String compname = formBean.getReqdata().getCompname();
		// 将  佣金 和 众包佣金 进行区分
		Integer type = formBean.getReqdata().getType();
		if (type == null || type <= 0) {
			type = 1;
		}

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CommissionFlowDto> commissionFlowDtoList = new ArrayList<>();
		BigDecimal remittedBrokerage = BigDecimal.ZERO;
		BigDecimal unremittedBrokerage = BigDecimal.ZERO;
		if (type == 1) {
			String amounttype = StringUtils.joinWith(",", 1, 2);//计佣类型
			commissionFlowDtoList = partnerAccountflowMapper.getPartnerAccountFlow(partnerId, compname, amounttype);
			unremittedBrokerage = partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerId, PartnerBrokerageState.SETTLED);
			remittedBrokerage = partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerId, PartnerBrokerageState.WITHDRAWING);
			remittedBrokerage = remittedBrokerage.add(
					partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerId, PartnerBrokerageState.WITHDRAWED));
		} else if (type == 2) {
			String amounttype = "3";
			commissionFlowDtoList = partnerAccountflowMapper.getPartnerAccountFlow(partnerId, compname, amounttype);
			unremittedBrokerage = partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerId, PartnerBrokerageState.SETTLED);
			remittedBrokerage = partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerId,
					PartnerBrokerageState.WITHDRAWING);
			remittedBrokerage = remittedBrokerage.add(
					partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerId, PartnerBrokerageState.WITHDRAWED));
		} else if (type == 3) {//作废
			// 众包成本佣金
			commissionFlowDtoList = partnerMonthlyCrowdCostMapper.listMonthlyCost(partnerId, 0).stream().map(cc -> {
				CommissionFlowDto dto = new CommissionFlowDto();
				dto.setCreatetime(cc.getCreatetime());
				dto.setFlowAmount(cc.getTotalProfit());
				dto.setFlowtype(1);
				dto.setCreatetime(cc.getCreatetime());
				return dto;
			}).collect(Collectors.toList());
			unremittedBrokerage = partnerMonthlyCrowdCostMapper.sumPartnerBrokerage(partnerId, PartnerCrowdsourceCostState.UNSETTLED);
			remittedBrokerage = partnerMonthlyCrowdCostMapper.sumPartnerBrokerage(partnerId, PartnerCrowdsourceCostState.WITHDRAWED);
		} else if (type == 4) {
			// 查询 其他佣金 流水
			String amounttype = "6";
			commissionFlowDtoList = partnerAccountflowMapper.getPartnerAccountFlow(partnerId, compname, amounttype);
			unremittedBrokerage = partnerBrokerageMapper.getOtherBrokerageByPartnerId(partnerId, PartnerBrokerageState.SETTLED);
			remittedBrokerage = partnerBrokerageMapper.getOtherBrokerageByPartnerId(partnerId, PartnerBrokerageState.WITHDRAWING);
			remittedBrokerage = remittedBrokerage.add(
					partnerBrokerageMapper.getOtherBrokerageByPartnerId(partnerId, PartnerBrokerageState.WITHDRAWED));
		}

		PartnerCommissionFlowDto partnerCommissionFlowDto = new PartnerCommissionFlowDto();
		partnerCommissionFlowDto.setRemittedBrokerage(remittedBrokerage);
		partnerCommissionFlowDto.setUnremittedBrokerage(unremittedBrokerage);
		partnerCommissionFlowDto.setCommissionFlowDtoList(commissionFlowDtoList);

		smartResult.setObject(partnerCommissionFlowDto)
				.setCurrpage(page.getPageNum())
				.setTotalpages(page.getPages())
				.setTotalrecords((int) page.getTotal());
		return smartResult;
	}

	/**
	 * 查取推荐企业与项目佣金
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult getPartnerCompany(BaseSimpleFormBean formBean) {
		SmartResult smartResult = new SmartResult();
		int partnerId = formBean.getUserid();
		if (partnerId == 0) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		partnerCompanyMapper.getPartnerCompanyBrokerageInfoByPartnerId(partnerId)
				.forEach(info -> info.setBrokerage(partnerBrokerageMapper.getTotalBrokerageByCompid(info.getCompid(), partnerId)));
		return smartResultPage(page);
	}

	/**
	 * 设置提现密码
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult updatePartnerDfPwd(BaseSimpleFormBean<PartnerDfPwdFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();
		PartnerDfPwdFormBean partnerDfPwdFormBean = baseSimpleFormBean.getReqdata();
		//校验参数
		if (null == partnerDfPwdFormBean || StringUtil.isEmpty(partnerDfPwdFormBean.getPayPassword()) ||
				baseSimpleFormBean.getIdtype() != UserType.PARTNER) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		//获取提现密码与合伙人ID
		String partnerDfPwd = partnerDfPwdFormBean.getPayPassword();
		int partnerid = baseSimpleFormBean.getUserid();
		//获取合伙人实名信息
		PartnerAccount partnerAccount = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		//校验合伙人是否存在实名信息
		if (null == partnerAccount) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		}
		//提现密码加盐
		String salt = RandomUtil.generateString(8);
		partnerAccount.setSalt(salt);
		partnerAccount.setPayPassword(MD5Util.md5(partnerDfPwd + salt));
		//更新
		partnerAccount.updateById();
		return smartResult;
	}

	/**
	 * 忘记提现密码
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult PartnerForgetDfPwd(BaseSimpleFormBean<PartnerForgetDfPwdFormBean> formBean) {
		SmartResult smartResult = new SmartResult();
		PartnerForgetDfPwdFormBean partnerForgetDfPwdFormBean = formBean.getReqdata();
		//校验参数
		if (null == partnerForgetDfPwdFormBean || StringUtil.isEmpty(partnerForgetDfPwdFormBean.getPayPassword()) ||
				formBean.getIdtype() != UserType.PARTNER) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		//获取合伙人ID
		int partnerid = formBean.getUserid();
		//获取手机号
		String phone = partnerForgetDfPwdFormBean.getPhone();
		//获取验证码
		String verifyCode = partnerForgetDfPwdFormBean.getVerifycode();
		//查询合伙人信息
		Partner partner = new Partner().selectById(partnerid);
		if (null == partner) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		}
		//校验手机号
		if (!partner.getPhone().equals(phone)) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_114);
			return smartResult;
		}

		commonService.checkPhoneVerifyCode(phone, verifyCode);

		//获取合伙人实名信息
		PartnerAccount partnerAccount = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		if (null == partnerAccount) {
			return smartResult(StatusMsg.StatusMsg_501);
		}
		String salt = RandomUtil.generateString(8);
		partnerAccount.setSalt(salt);
		partnerAccount.setPayPassword(MD5Util.md5(partnerForgetDfPwdFormBean.getPayPassword() + salt));
		partnerAccount.updateById();
		return smartResult();
	}

	/**
	 * 校验提现密码
	 *
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult checkPartnerDfPwd(BaseSimpleFormBean<PartnerDfPwdFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();
		PartnerDfPwdFormBean partnerDfPwdFormBean = baseSimpleFormBean.getReqdata();
		//校验参数
		if (null == partnerDfPwdFormBean || StringUtil.isEmpty(partnerDfPwdFormBean.getPayPassword()) ||
				baseSimpleFormBean.getIdtype() != UserType.PARTNER) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		//获取合伙人提现密码和合伙人ID
		String partnerPayPwd = partnerDfPwdFormBean.getPayPassword();
		int partnerid = baseSimpleFormBean.getUserid();

		PartnerAccount partnerAccount = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		if (null == partnerAccount) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_501);
			return smartResult;
		}
		String salt = partnerAccount.getSalt();
		String md5PayPwd = MD5Util.md5(partnerPayPwd + salt);
		if (!md5PayPwd.equals(partnerAccount.getPayPassword())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_113);
			return smartResult;
		}
		return smartResult;
	}

	/**
	 * 绑定银行卡
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult partnerBankcardAuth(BaseSimpleFormBean<PartnerBankcardAuthFormBean> formBean) {
		PartnerBankcardAuthFormBean reqdata = formBean.getReqdata();
		//获取合伙人ID
		int partnerid = formBean.getUserid();
		//校验参数
		if (partnerid <= 0 || reqdata == null) return errorParamSmartResult();

		JSONObject jsonObject = bankCardElementCertificationService.homeQuery(reqdata.getAcctno());
		if (!BankCardElementCertificationService.TYPE.equals(jsonObject.getString("type"))){
			return smartResult(StatusMsg.BANKCARD_TYPE);
		}
		//现将其他已经绑了的银行卡置为失效
		new PartnerBankcard().setState(2).update(Condition.create().eq("partnerid", partnerid));
		//检查是否存在这张卡
		PartnerBankcard partnerBankcard = new PartnerBankcard().selectOne(
				Condition.create().eq("partnerid", partnerid).eq("acctno", reqdata.getAcctno()));
		if (partnerBankcard != null) {
			partnerBankcard.setState(1);
		} else {
			partnerBankcard = new PartnerBankcard().setPartnerid(partnerid).setState(1);
		}
		BeanUtils.copyProperties(reqdata, partnerBankcard);
		if (partnerBankcard.insertOrUpdate()) {
			return smartResult();
		}
		return optFailSmartResult();
	}

	public SmartResult<PartnerWithdrawDto> getWithdrawInfo(BaseSimpleFormBean formBean) {
		int partnerid = formBean.getUserid();
		int idtype = formBean.getIdtype();
		if (partnerid <= 0 || idtype != 3) return errorParamSmartResult();

		BigDecimal totalBrokerage = partnerBrokerageMapper.getTotalNormalBrokerageWithState(partnerid, PartnerBrokerageState.SETTLED);
		if (totalBrokerage == null) totalBrokerage = BigDecimal.ZERO;
		BigDecimal crowdsourceBrokerage = partnerBrokerageMapper.getTotalCrowdsourceBrokerageByPartnerId(partnerid,
				PartnerBrokerageState.SETTLED);
		BigDecimal crowdCostBrokerage = partnerMonthlyCrowdCostMapper.sumPartnerBrokerage(partnerid,
				PartnerCrowdsourceCostState.UNSETTLED);

		PartnerBankcard validCard = partnerBankcardMapper.getValidCard(partnerid);
		if (validCard == null) return smartResult(StatusMsg.StatusMsg_206);

		PartnerWithdrawDto dto = new PartnerWithdrawDto();
		BeanUtils.copyProperties(validCard, dto);
		dto.setPartnerid(partnerid).setTotalBrokerage(totalBrokerage).setCrowdsourceBrokerage(crowdsourceBrokerage.add(crowdCostBrokerage));

		return smartResult(dto);
	}

	public SmartResult commitWithdraw(BaseSimpleFormBean formBean) {
		int partnerid = formBean.getUserid();
		int idtype = formBean.getIdtype();
		if (partnerid <= 0 || idtype != 3) return errorParamSmartResult();

		return corePartnerService.handleWithdrawInternal(0, partnerid);
	}

	public SmartResult<PartnerStudioWithdrawDto> listPartnerStudioWithdraws(
			BaseSimpleFormBean<ListPartnerStudioWithdrawsFromBean> formBean) {
		@Valid ListPartnerStudioWithdrawsFromBean reqdata = formBean.getReqdata();
		int state = reqdata.getState();
		Date from = reqdata.getFrom();
		Date to = reqdata.getTo();
		int partnerid = formBean.getUserid();

		Page<PartnerStudioWithdrawDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		partnerStudioWithdrawMapper.listByPartnerid(partnerid, state, from, to);

		return SmartResult.ofPage(page);
	}

	public SmartResult createShareImg(BaseSimpleFormBean<String> formBean) {
		String name = formBean.getReqdata();
		int partnerid = formBean.getUserid();
		int idtype = formBean.getIdtype();

		Partner partner = new Partner().selectById(partnerid);
		if (partner == null) return errorParamSmartResult();
		PartnerAccount account = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));

		PartnerShareImg shareImg = new PartnerShareImg().selectById(partnerid);
		if (shareImg != null) {
			//删除旧图片
			FileUtil.deleteFile(new File(uploadPathConfig.getUploadpath(), shareImg.getImgpath()));
		}

		try {
			// ClassPathResource resource = new ClassPathResource("img/poster.png");
			// InputStream srcIs = resource.getInputStream();
			File posterFile = new File(uploadPathConfig.getPromoPosterPath());
			InputStream srcIs = new FileInputStream(posterFile);

			String uploadpath = uploadPathConfig.getUploadpath();
			String date = DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_8);
			File pathFile = new File(uploadpath, date);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			String filename = RandomUtil.createRandomNo("SHARE_", ".png");
			File outputImageFile = new File(pathFile, filename);

			try (OutputStream os = new FileOutputStream(outputImageFile)) {
				BufferedImage srcImg = ImageIO.read(srcIs);

				//画名字
				Font font = new Font("宋体", Font.PLAIN, 40);
				int textX = 65;
				int textY = 179;
				Graphics2D graphics = srcImg.createGraphics();
/*				graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
				graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
						null);*/

				graphics.setColor(Color.white);
				graphics.setFont(font);

				graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));

				graphics.drawString(name, textX, textY);
				graphics.dispose();

				//画推广码
				Font font2 = new Font("宋体", Font.PLAIN, 24);
				int textX2 = 500;
				int textY2 = 69;
				graphics = srcImg.createGraphics();
/*				graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
				graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
						null);*/

				graphics.setColor(Color.white);
				graphics.setFont(font2);

				graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));

				graphics.drawString("<好友邀请码" + account.getPromoCode() + ">", textX2, textY2);
				graphics.dispose();

				//画头像
				String avatar = partner.getAvatar();
				InputStream avatarIs = null;
				if (StringUtil.isEmpty(avatar)) {
					// ClassPathResource avatarRes = new ClassPathResource("img/default_avatar.png");
					// avatarIs = avatarRes.getInputStream();
					File defaultAvatarFile = new File(uploadPathConfig.getDefaultAvatarPath());
					avatarIs = new FileInputStream(defaultAvatarFile);
				} else {
					URL url = new URL(avatar);
					avatarIs = url.openStream();
				}
				int avatarX = 60;
				int avatarY = 37;
				int avatarWidth = 90;
				int avatarHeight = 90;

				ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(avatarIs));
				Image logoImg = logoImgIcon.getImage();
				Image scaleLogo = logoImg.getScaledInstance(avatarWidth, -1, Image.SCALE_DEFAULT);

				graphics = srcImg.createGraphics();
				graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				//绘制圆形的头像区域
				Ellipse2D.Double shape = new Ellipse2D.Double(avatarX, avatarY, avatarWidth, avatarHeight);
				graphics.setClip(shape);

				graphics.setColor(Color.WHITE);
				graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));

				//水印 的位置
				graphics.drawImage(scaleLogo, avatarX, avatarY, null);
				graphics.dispose();

				// 生成图片
				ImageIO.write(srcImg, FileUtil.getFileExtension(outputImageFile.getName()), os);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String pathurl = date + File.separator + filename;
			PartnerShareImg partnerShareImg = new PartnerShareImg().setPartnerid(partnerid).setName(name).setImgpath(pathurl);

			if (partnerShareImg.insertOrUpdate()) {
				return smartResult(partnerShareImg);
			}
		} catch (Exception e) {
			log.error("生成推广海报失败：", e);
		}
		return optFailSmartResult();
	}

	public SmartResult getShareImg(BaseSimpleFormBean<Integer> formBean) {
		Integer partnerid = formBean.getReqdata();
		return smartResult(new PartnerShareImg().selectById(partnerid));
	}

	public SmartResult addShareUser(BaseSimpleFormBean<AddShareUserFormBean> formBean) {
		SmartResult smartResult = new SmartResult();
		AddShareUserFormBean reqdata = formBean.getReqdata();
		if (formBean.getReqdata() == null || StringUtil.isEmpty(reqdata.getWxcode())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int partnerid = reqdata.getPartnerid();
		String wxcode = reqdata.getWxcode();

		Partner partner = new Partner().selectById(partnerid);
		if (partner == null) return smartResult(StatusMsg.StatusMsg_501);

		WxAuthorizeAccessToken authorizeAccessToken = wxApiService.getAuthorizeAccessToken(wxcode, wxPartnerConfig.getAppid(),
				wxPartnerConfig.getSecret());
		if (authorizeAccessToken == null) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String openid = authorizeAccessToken.getOpenid();
		String accessToken = authorizeAccessToken.getAccess_token();

		if (StringUtil.isEmpty(openid) || StringUtil.isEmpty(accessToken)) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int count = new PartnerShareUser().selectCount(Condition.create().eq("partnerid", partnerid).eq("openid", openid));
		if (count > 0) return smartResult;

		WxAuthorizeUserInfo authorizeUserInfo = wxApiService.getAuthorizeUserInfo(accessToken, openid);
		if (authorizeUserInfo == null) {
			return optFailSmartResult();
		}

		if (authorizeUserInfo.getOpenid().equals(partner.getOpenid())) {
			//是合伙人自己，不添加
			return smartResult;
		}

		PartnerShareUser shareUser = new PartnerShareUser().setPartnerid(partnerid)
				.setOpenid(authorizeUserInfo.getOpenid())
				.setUnionid(authorizeUserInfo.getUnionid())
				.setNickname(authorizeUserInfo.getNickname())
				.setAvatar(authorizeUserInfo.getHeadimgurl())
				.setSex(StringUtil.toInt(authorizeUserInfo.getSex()));
		if (shareUser.insert()) {
			return smartResult(shareUser.getUserid());
		}

		return optFailSmartResult();
	}

	public SmartResult getShareUserList(BaseSimpleFormBean formBean) {
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		new PartnerShareUser().selectList(Condition.create().eq("partnerid", formBean.getUserid()).orderBy("createtime", false));

		return smartResultPage(page);
	}

	/**
	 * 获取合同中某些合伙人字段
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult queryGivenField(BaseSimpleFormBean formBean) {
		if (null == formBean || 0 == formBean.getUserid()) {
			return errorParamSmartResult();
		}
		PartnerAccount partnerAccount = partnerAccountMapper.getPartnerAccountByPartnerId(formBean.getUserid());
		PartnerGivenFieldDto partnerGivenFieldDto = new PartnerGivenFieldDto();
		BeanUtils.copyProperties(partnerAccount, partnerGivenFieldDto);
		Partner partner = new Partner().selectById(partnerGivenFieldDto.getPartnerid());
		partnerGivenFieldDto.setPhone(partner.getPhone());
		PartnerBankcard partnerBankcard = partnerBankcardMapper.getValidCard(formBean.getUserid());
		if (null != partnerBankcard) {
			if (StringUtil.isNotEmpty(partnerBankcard.getBankname())) {
				partnerGivenFieldDto.setBankname(partnerBankcard.getBankname());
			}
			if (StringUtil.isNotEmpty(partnerBankcard.getAcctno())) {
				partnerGivenFieldDto.setAcctno(partnerBankcard.getAcctno());
			}
		}
		BusinessManager businessManager = new BusinessManager().selectById(partnerAccount.getBusinessManagerId());
		if (businessManager != null) {
			partnerGivenFieldDto.setBusinessManagerId(businessManager.getBusinessManagerId());
			partnerGivenFieldDto.setBusinessManager(businessManager.getBusinessManager());
			partnerGivenFieldDto.setNickname(businessManager.getNickname());
			partnerGivenFieldDto.setBusinessEmail(businessManager.getEmail());
			partnerGivenFieldDto.setBusinessPhone(businessManager.getPhone());
		}
		return smartResult(partnerGivenFieldDto);
	}

	public SmartResult submitRecommendCompany(BaseSimpleFormBean<SubmitRecommendCompanyFormBean> formBean) {
		SubmitRecommendCompanyFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int partnerid = formBean.getUserid();
		int idtype = formBean.getIdtype();
		if (idtype != UserType.PARTNER || partnerid <= 0) return smartResult(StatusMsg.StatusMsg_501);

		Partner partner = new Partner().selectById(partnerid);
		if (partner == null) return smartResult(StatusMsg.StatusMsg_501);

		PartnerRecommendCompany recommendCompany = new PartnerRecommendCompany();
		BeanUtils.copyProperties(reqdata, recommendCompany);
		recommendCompany.setPartnerid(partnerid).setState(Constants.PARTNER_RECOMMEND_VERIFYING);
		recommendCompany.insert();
		return smartResult(recommendCompany.getId());
	}

	public SmartResult getRecommendCompanyList(BaseSimpleFormBean<RecommendCompanyListFormBean> formBean) {
		RecommendCompanyListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int partnerid = formBean.getUserid();
		String company = reqdata.getCompany();
		int partnerType = reqdata.getPartnerType();
		int state = reqdata.getState();

		Page page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		if (state == Constants.PARTNER_RECOMMEND_HANDLED) {
			partnerRecommendCompanyMapper.getEffectiveRecommendList(partnerid, company, partnerType);
		} else {
			partnerRecommendCompanyMapper.getRecommendListByPartnerid(partnerid, company, state, partnerType);
		}

		return smartResultPage(page);
	}

	public SmartResult getRecommendCompanyDetail(BaseSimpleFormBean<Integer> formBean) {
		return smartResult(partnerRecommendCompanyMapper.getRecommendCompany(formBean.getReqdata()));
	}

	/**
	 * 修改微信号和邮箱
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult updateWXNumberAndEmail(BaseSimpleFormBean<AuthenticationFormBean> formBean) {
		AuthenticationFormBean reqdata = formBean.getReqdata();
		if (reqdata == null || StringUtil.isEmpty(reqdata.getEmail()) || StringUtil.isEmpty(reqdata.getWechatNumber()) ||
				0 == formBean.getUserid()) {
			return errorParamSmartResult();
		}
		PartnerAccount partnerAccount = partnerAccountMapper.getPartnerAccountByPartnerId(formBean.getUserid());
		if (null == partnerAccount) {
			return smartResult(StatusMsg.StatusMsg_501);
		}
		partnerAccount.setWechatNumber(reqdata.getWechatNumber());
		partnerAccount.setEmail(reqdata.getEmail());
		if (!partnerAccount.updateById()) {
			return optFailSmartResult();
		}
		return smartResult();
	}

	public SmartResult orgPartnerLogin(BaseSimpleFormBean<OrgPartnerLoginFormBean> formBean) {
		@Valid OrgPartnerLoginFormBean reqdata = formBean.getReqdata();
		String loginname = reqdata.getLoginname();
		String password = reqdata.getPassword();

		Partner partner = partnerMapper.findByLoginname(loginname);
		if (partner == null) return SmartResult.fail(StatusMsg.StatusMsg_132);

		String salt = partner.getSalt();
		String savedPassword = partner.getPassword();
		if (!StringUtil.equals(MD5Util.md5(password + salt), savedPassword)) {
			return SmartResult.fail(StatusMsg.StatusMsg_132);
		}

		PartnerDetailDto partnerDetail = partnerMapper.getPartnerDetail(partner.getPartnerid());
		return SmartResult.success(partnerDetail);
	}

	public SmartResult bindStudio(BaseSimpleFormBean<BindStudioFromBean> formBean) {

		int partnerid = formBean.getUserid();
		@Valid BindStudioFromBean reqdata = formBean.getReqdata();
		PartnerAccount partnerAccount = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		if (partnerAccount == null || partnerAccount.getRealnameAuth() != 4) {
			return SmartResult.fail(StatusMsg.StatusMsg_504);
		}

		MakerAccount makerAccount = new MakerAccount().selectOne(
				Condition.create().eq("realname", reqdata.getRealname()).eq("idno", reqdata.getIdno()));
		if (makerAccount == null) return SmartResult.fail(StatusMsg.StatusMsg_201);
		MakerStudio makerStudio = new MakerStudio().selectById(makerAccount.getUserid());
		if (makerStudio == null || makerStudio.getState() != StudioState.CONFIRMED) return SmartResult.fail(StatusMsg.StatusMsg_204);

		partnerAccount.setStudioId(makerStudio.getUserid()).updateById();
		return smartResult();
	}

	public SmartResult listWithdrawRecord(BaseSimpleFormBean<ListWithdrawRecordFormBean> formBean) {
		int userid = formBean.getUserid();
		@Valid ListWithdrawRecordFormBean reqdata = formBean.getReqdata();
		int remitType = reqdata.getRemitType();
		Page<PartnerWithdrawRecordDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		if (remitType == RemitType.ONLINE) {
			partnerWithdrawMapper.listWithdrawRecord(userid);
		} else if (remitType == RemitType.OFFLINE) {
			partnerStudioWithdrawMapper.listWithdrawRecord(userid);
		}
		return SmartResult.ofPage(page);
	}

	public SmartResult<PartnerCompanyTotalBrokerageDto> listCompanyTotalBrokerage(BaseSimpleFormBean formBean) {
		int userid = formBean.getUserid();
		List<PartnerCompanyTotalBrokerageDto> list = partnerBrokerageMapper.sumBrokerageBySettleType(userid);
		return SmartResult.success(list);
	}

	public SmartResult<PartnerCompanyTotalProjectAmountDto> listCompanyTotalProjectAmount(BaseSimpleFormBean formBean) {
		int userid = formBean.getUserid();
		List<PartnerCompanyTotalProjectAmountDto> list = partnerBrokerageMapper.sumTotalProjectAmountByRemitState(userid);
		return SmartResult.success(list);
	}

	// 获取当前合伙人 每月成本分佣列表 根据合伙人id
	public SmartResult<PartnerMonthlyCostDto> listMonthlyCost(BaseSimpleFormBean<MonthlyCostFormBean> formBean) {
		MonthlyCostFormBean reqdata = formBean.getReqdata();
		Page<PartnerMonthlyCostDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		partnerMonthlyCrowdCostMapper.listMonthlyCost(reqdata.getPartnerid(), reqdata.getState());
		return SmartResult.ofPage(page);
	}

	// 查询每月成本分佣 详情列表 根据成本id
	public SmartResult<PartnerCompanyMonthlyCrowdourceCostDto> listCompanyMonthlyCost(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer costId = formBean.getReqdata();
		List<PartnerCompanyMonthlyCrowdourceCostDto> list = partnerCompanyMonthlyCrowdCostMapper.listByCostId(costId);
		return SmartResult.success(list);
	}

	public SmartResult retrieveVaccinePoster(BaseSimpleFormBean<Integer> formBean) {
		int partnerid = formBean.getUserid();
		Integer compid = formBean.getReqdata();

		PartnerAccount account = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		Asserts.notNull(account, StatusMsg.StatusMsg_501);
		Company company = new Company().selectById(compid);
		Asserts.notNull(company, StatusMsg.StatusMsg_302);
		Asserts.equals(account.getVaccineFlag(), Constants.TRUE, StatusMsg.StatusMsg_525);

		// Already generated the poster, return it
		if (StringUtil.isNotEmpty(account.getVaccinePoster())) {
			return SmartResult.success(account.getVaccinePoster());
		}

		try {
			// ClassPathResource resource = new ClassPathResource("img/poster.png");
			// InputStream srcIs = resource.getInputStream();
			File posterFile = new File(uploadPathConfig.getVaccinePosterPath());
			InputStream srcIs = new FileInputStream(posterFile);

			String date = DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_8);
			File pathFile = new File(uploadPathConfig.getUploadpath(), date);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			String filename = RandomUtil.createRandomNo("vaccine_", ".png");
			File outputImageFile = new File(pathFile, filename);

			try (OutputStream os = new FileOutputStream(outputImageFile)) {
				BufferedImage srcImg = ImageIO.read(srcIs);

				// 生成二维码
				String url = String.format(zddUrlConfig.getPartnerVaccinePosterFormUrl(), partnerid, compid);
				ByteArrayOutputStream qrcodeOs = new ByteArrayOutputStream();
				QrcodeUtil.encode(url, qrcodeOs);
				InputStream qrcodeIs = new ByteArrayInputStream(qrcodeOs.toByteArray());

				//画二维码
				int qrcodeX = 448;
				int qrcodeY = 1990;
				int qrcodeWidth = 192;
				int qrcodeHeight = 192;

				ImageIcon qrcodeImgIcon = new ImageIcon(ImageIO.read(qrcodeIs));
				Image qrcodeImg = qrcodeImgIcon.getImage();
				Image scaleQrcode = qrcodeImg.getScaledInstance(qrcodeWidth, -1, Image.SCALE_DEFAULT);

				Graphics2D graphics = srcImg.createGraphics();
				graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				// //绘制圆形的头像区域
				// Ellipse2D.Double shape = new Ellipse2D.Double(qrcodeX, qrcodeY, qrcodeWidth, qrcodeHeight);
				// graphics.setClip(shape);

				graphics.setColor(Color.WHITE);
				graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));

				//水印 的位置
				graphics.drawImage(scaleQrcode, qrcodeX, qrcodeY, null);
				graphics.dispose();

				// 生成图片
				ImageIO.write(srcImg, FileUtil.getFileExtension(outputImageFile.getName()), os);
				qrcodeOs.close();
				qrcodeIs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

			String pathurl = date + File.separator + filename;
			account.setVaccineCompid(compid).setVaccinePoster(pathurl);

			if (account.updateById()) {
				return SmartResult.success(pathurl);
			}
		} catch (Exception e) {
			log.error("生成推广海报失败：", e);
		}
		return SmartResult.ofOptFail();
	}

	public SmartResult savePartnerVaccineRecord(BaseSimpleFormBean<PartnerVaccineRecordFormBean> formBean) {
		PartnerVaccineRecordFormBean reqdata = formBean.getReqdata();
		Integer partnerid = reqdata.getPartnerid();
		PartnerAccount account = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		Asserts.notNull(account, StatusMsg.StatusMsg_501);
		Asserts.equals(account.getVaccineFlag(), Constants.TRUE, StatusMsg.StatusMsg_525);

		MarketingCooperativeRecord record = reqdata.toMCEntity();
		if (record.insert()) {
			// 发送微信消息给胡晓峰
			wxPartnerMessageService.notifyPartnerApplyMarketingCooperativeRecord(record);
		}
		return SmartResult.success();
	}

	public SmartResult<PartnerVaccineRecordDto> listPartnerVaccineRecords(BaseSimpleFormBean<PartnerVaccineRecordListFormBean> formBean) {
		int partnerId = formBean.getUserid();
		PartnerVaccineRecordListFormBean reqdata = formBean.getReqdata();
		int state = reqdata.getState();

		PartnerAccount account = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerId));
		Asserts.notNull(account, StatusMsg.StatusMsg_501);
		Asserts.equals(account.getVaccineFlag(), Constants.TRUE, StatusMsg.StatusMsg_525);

		Page<PartnerVaccineRecordDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		partnerVaccineRecordMapper.listByPartnerid(partnerId, state);
		return SmartResult.ofPage(page);
	}

	public SmartResult getVaccinePoster(int partnerid) {
		PartnerAccount account = new PartnerAccount().selectOne(Condition.create().eq("partnerid", partnerid));
		Asserts.notNull(account, StatusMsg.StatusMsg_501);
		Asserts.equals(account.getVaccineFlag(), Constants.TRUE, StatusMsg.StatusMsg_525);

		// Already generated the poster, return it
		if (StringUtil.isNotEmpty(account.getVaccinePoster())) {
			return SmartResult.success(account.getVaccinePoster());
		}
		return SmartResult.fail(StatusMsg.StatusMsg_524);
	}
}
